package com.coolw.jdbc.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库工具类
 *
 * @author coolw
 * @date 2023/12/9 12:01
 */
public final class DbUtil {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        Properties prop = new Properties();
        try (InputStream is = DbUtil.class.getClassLoader().getResourceAsStream("jdbc.properties")) {
            // 加载配置文件
            prop.load(is);

            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws Exception {
        // 注册驱动
        Class.forName(driver);
        // 获取连接
        return DriverManager.getConnection(url, username, password);
    }

    /**
     * 关闭资源:关闭顺序与使用顺序相反，依次关闭顺序为ResultSet,Statement,Connection
     */
    public static void close(Connection conn, Statement stat, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
